package tcp;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        System.out.println("------服务端启动------");
        ServerSocket serverSocket = null;
        Socket socket = null;
        DataInputStream dataInputStream = null;
        try {
            //创建ServerSocket对象，同时为服务端注册端口
            serverSocket = new ServerSocket(9999);
            //使用ServerSocket对象，调用accept方法，等到客户端链接
            socket = serverSocket.accept();
            //从端点socket得到一个字节流
            InputStream inputStream = socket.getInputStream();
            //把字节流包装成数据流
            dataInputStream = new DataInputStream(inputStream);
            //使用数据流读取客户端数据
            String s = dataInputStream.readUTF();
            System.out.println(s);
            System.out.println(socket.getRemoteSocketAddress());
        } catch (Exception ignored) {

        }finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
                if (socket != null) {
                    socket.close();
                }
                if (dataInputStream != null) {
                    dataInputStream.close();
                }
            } catch (Exception ignored) {

            }
        }
    }
}
